package com.ben.multiple.message.base;

import com.ben.multiple.message.base.tencent.TencentMessageAutoConfig;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author BenJin Yin
 * @date 2020/7/23
 */
@Configuration
@ConditionalOnBean(MessageClient.class)
@AutoConfigureAfter({ TencentMessageAutoConfig.class})
@EnableConfigurationProperties(MessageProperties.class)
public class MessageAutoConfig {

    private final MessageProperties properties;

    private final Map<MessageProperties.Type, MessageClient> clientMap = new ConcurrentHashMap<>();

    public MessageAutoConfig(MessageProperties properties,
                             ObjectProvider<List<? extends MessageClient>> clientProvider) {
        this.properties = properties;
        clientProvider.ifAvailable(list -> list.forEach(obj -> clientMap.put(obj.getType(), obj)));
    }

    @Bean
    @ConditionalOnMissingBean
    public MessageService messageService() {
        MessageClient client;
        if (properties.getType() == null) {
            client = clientMap.get(MessageProperties.Type.ALIYUN);
            if (client != null) {
                return new MessageService(client);
            }
            client = clientMap.get(MessageProperties.Type.TENCENT);
            if (client != null) {
                return new MessageService(client);
            }
            throw new RuntimeException("no available MessageClient bean");
        }
        client = clientMap.get(properties.getType());
        if (client == null) {
            throw new RuntimeException("no available FileClient bean");
        }
        return new MessageService(client);
    }
}
